/**
 * 描述: 后端产品分类-故障图片详情页
 *
 * @author yangshuangping
 * @since 2021/11/18 18:37
 */
var $ = layui.$;
layui.define(['index', 'form', 'table', 'laypage', 'layedit', 'upload'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let layer = layui.layer;
    let upload = layui.upload;

    form.render(null, "zmn-form");
    // 初始化文件上传插件
    reLoadImage("faultImgSrc", json.categoryFaultImage.faultImg, "faultImgSrcValue");
    uploaderImage("faultImgSrc", "faultImgSrcValue", "png|jpg|jpeg", 1024 * 5);

    // 初始化文件上传插件
    reLoadImage("defaultImgSrc", json.categoryFaultImage.defaultImg, "defaultImgSrcValue");
    uploaderImage("defaultImgSrc", "defaultImgSrcValue", "png|jpg|jpeg", 1024 * 5);

    // 自定义验证规则
    form.verify({
        coord: function (value) {
            if (!coordinate(value)) {
                return "坐标输入格式不对！填写逗号隔开的数字！";
            }
        },
        defaultImg: function (value) {
            if (zmnUtil.isEmptyNull(value)) {
                return "请上传默认图片！";
            }
        }
    });

    if (json.listPitchOnFault.length > 0 && json.listFault.length > 0) {
        json.listFault.forEach(function (item) {
            json.listPitchOnFault.forEach(val => {
                if (item.value == val.value) {
                    item.selected = true;
                }
            })
        })
    }

    xmSelect.render({
        el: '#faultRelevance',
        language: 'zn',
        tips: '如有关联故障，请选择，非必填',
        prop: {name: 'text', value: 'value'},
        name: 'faultRelevance',
        filterable: true,
        direction: 'auto',
        paging: true,
        pageSize: 10,
        model: {
            label: {
                type: 'block',
                block: {
                    //最大显示数量, 0:不限制
                    showCount: 1,
                    //是否显示删除图标
                    showIcon: true,
                }
            }
        },
        filterMethod: function (val, item, index, prop) {
            if (val == item.value) {//把value相同的搜索出来
                return true;
            }
            if (item.text.indexOf(val) != -1) {//名称中包含的搜索出来
                return true;
            }
            return false;//不知道的就不管了
        },
        data: json.listFault
    })

    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {
        let data = obj.field;
        let url = "/category/faultimage/addEdit.action";

        if (!zmnUtil.isEmptyNull(data.faultRelevance)) {
            if (zmnUtil.isEmptyNull(data.faultImg)) {
                layer.alert("请上传故障图片！");
                return false;
            }
        }

        if (!zmnUtil.isEmptyNull(data.faultCoord)) {
            if (zmnUtil.isEmptyNull(data.faultRelevance)) {
                layer.alert("请选择关联故障！");
                return false;
            }
            if (!coordinate(data.faultCoord)) {
                layer.alert("坐标输入格式不对,请填写正确的坐标值！");
                return false;
            }
        }

        if (!zmnUtil.isEmptyNull(data.faultImg)) {
            if (zmnUtil.isEmptyNull(data.faultRelevance)) {
                layer.alert("请选择关联故障！");
                return false;
            }
            if (zmnUtil.isEmptyNull(data.faultCoord)) {
                layer.alert("请填写故障文案坐标！");
                return false;
            }
        }

        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            success: function (result) {
                if (result.status == 200) {
                    layer.msg(result.data, {"icon": 1, "time": 1000}, function () {
                        parent.location.reload();
                    });
                } else {
                    layer.msg(result.message, {"icon": 2});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }
        })
        return false;
    });

    /**
     * 描述: 图片上传方法
     * @param elemId
     * @param valueId
     */
    let indexUploadImags;

    function uploaderImage(elemId, selectorId, exts, size) {
        let folderName = "servCategFault/" + json.categoryFaultImage.groupId
        upload.render({
            elem: '#' + elemId,
            exts: exts,
            acceptMime: 'image/*',
            accept: 'images',
            url: '/common/uploadFile.action?folderName=' + folderName,
            size: size,
            before: function (obj) {
                indexUploadImags = layui.layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            }, done: function (res) {
                if (res.code == 2) {
                    var data = res.data;
                    $("#" + selectorId).val(data.src);
                    $("#" + elemId).attr("style",
                        "background:url( " + data.src + "?" + Date.now() +
                        ");background-size:100% 100%;background-repeat:no-repeat;");
                    let next = $("#" + selectorId).next();
                    let next1 = $(next).next();
                    $(next).attr("style", "visibility:hidden !important");
                    $(next1).attr("style", "visibility:hidden !important");
                } else {
                    layer.msg("上传失败！")
                }
                layui.layer.close(indexUploadImags);
            }
        });
    }

    function reLoadImage(elemId, value, valueId) {
        zmnUploadUtil.reLoadImage($, elemId, value, valueId);
    }

    // 坐标格式校验
    function coordinate(value) {
        let symbol = ",";
        let list = value.split(symbol)
        let reg = /^[-\+]?[1-9]\d*\,[-\+]?[1-9]\d*$/;
        return (reg.test(value) && list.length === 2)

    }

    //对外暴露的接口
    exports('category_faultimage_detail', {});
});

/**
 * 删除图片
 * @param element
 */
function deleteImg(element) {
    var elementValue = element + 'Value';
    document.getElementById(element).removeAttribute('style');
    Array.from(document.getElementById(element).children).forEach(function (item) {
        item.removeAttribute('style');
    });
    document.getElementById(elementValue).removeAttribute('value');
}

/**
 * 预览图片
 * @param element
 */
function previewImg(element) {
    // 调整预览大小
    var img = new Image();
    img.src = $('#' + element).attr('value');
    var imgHtml = "<img src='" + img.src + "' width='100%' height='100%'/>";
    // 弹出层
    layer.open({
        type: 1,
        shade: 0.8,
        offset: 'auto',
        area: [600 + 'px', 300 + 'px'],
        shadeClose: true,
        scrollbar: false,
        // 不显示标题
        title: "",
        // 捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        content: imgHtml,
        cancel: function () {
            //layer.msg('捕获就是从页面已经存在的元素上，包裹layer的结构', { time: 5000, icon: 6 });
        }
    });


}